package com.meisupic.copyright.notify;

import java.util.concurrent.DelayQueue;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

/**
 * @Author lanjian
 * @Date 2018/4/7 下午10:07
 */
@Component
public class NotifyTaskPool {

  public static DelayQueue<NotifyTask> tasks = new DelayQueue<NotifyTask>();

  @Autowired
  private ThreadPoolTaskExecutor threadPool;

  @PostConstruct
  public void start() {
    startThread();
  }

  private void startThread() {
    threadPool.execute(new Runnable() {
      @Override
      public void run() {
        while (true) {
          try {
            if (threadPool.getActiveCount() < threadPool.getMaxPoolSize()) {
              final NotifyTask task = tasks.poll();
              if (task != null) {
                threadPool.execute(new Runnable() {
                  public void run() {
                    tasks.remove(task);
                    task.run();
                  }
                });
              }
            }
            Thread.sleep(1000);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
    });
  }
}
